package cn.study.server.handler;

import cn.study.message.LoginRequestMessage;
import cn.study.message.LoginResponseMessage;
import cn.study.server.service.UserService;
import cn.study.server.service.UserServiceFactory;
import cn.study.server.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author Zsz
 * @Date 2022/4/4 21:11
 * @Version 1.0
 **/
@Slf4j
@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, LoginRequestMessage msg) throws Exception {
        String username = msg.getUsername();
        String password = msg.getPassword();
        UserService userService = UserServiceFactory.getUserService();
        boolean login = userService.login(username, password);
        if (login) {
            SessionFactory.getSession().bind(channelHandlerContext.channel(), msg.getUsername());
            LoginResponseMessage responseMessage = new LoginResponseMessage(true, "登陆成功！");
            channelHandlerContext.writeAndFlush(responseMessage);
        } else {
            LoginResponseMessage responseMessage = new LoginResponseMessage(false, "登陆失败！");
            channelHandlerContext.writeAndFlush(responseMessage);
        }
    }
}
